<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/about' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card style="margin-top: 20px">
      <!-- 搜索 -->
      <el-row>
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <el-input
              v-model="keyword"
              :clearable="true"
              @clear="clearsearch"
              placeholder="请输入内容"
            >
              <el-button
                slot="append"
                @click="search"
                icon="el-icon-search"
              ></el-button>
            </el-input></div
        ></el-col>
        <el-col :span="4">
          <el-button type="primary" style="margin-left: 20px" @click="add" plain
            >添加用户</el-button
          >
        </el-col>
      </el-row>
    <!-- 表格 --> 
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="#" width="170"> </el-table-column>
      <el-table-column prop="username" label="姓名" width="150">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="150"> </el-table-column>
      <el-table-column prop="mobile" label="电话" width="150">
      </el-table-column>
      <el-table-column prop="role_name" label="角色" width="150">
      </el-table-column>
      <el-table-column prop="mg_state" label="状态" width="150">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            active-color="#409eff"
            @change="changeState(scope.row)"
            inactive-color="#dcdfe6"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            @click="handleEdit(scope.$index, scope.row)"
            icon="el-icon-edit"
            circle
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.$index, scope.row)"
            circle
          ></el-button>
          <el-button type="warning" @click="handleAdd(scope.$index, scope.row)" icon="el-icon-star-off" circle></el-button>
        </template>
      </el-table-column>
    </el-table> 
 

      <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[5, 8, 10, 15]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    </el-card>
      

    <!-- 添加的弹框 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 编辑的弹框 -->
    <el-dialog title="编辑用户" :visible.sync="dialogFormVisible1">
      <el-form
        :model="ruleForm1"
        :rules="rules"
        ref="ruleForm1"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm1.username"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm1.email"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile">
          <el-input v-model="ruleForm1.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="submitForm1"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 角色分配的弹框 -->
     <el-dialog title="分配角色" :visible.sync="dialogFormVisible2">
      <el-form   
        ref="ruleForm2"
        label-width="100px"
        class="demo-ruleForm"
        :model="userInfo"
      >
        <el-form-item label="当前用户" prop="username">
          {{userInfo.username}}
         </el-form-item>

        <el-form-item label="当前角色" prop="role_name">
           {{userInfo.role_name}}
        </el-form-item>

          <el-form-item label="分配角色" prop="role_name">
    <el-select  v-model="roleId" placeholder="请选择文章标签">
      <el-option v-for="item in ruleForm2" :key="item.id"
       :label="item.role_name" 
       :value="item.id"></el-option> 
    </el-select>
  </el-form-item>
 
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="submitForm2"
          >确 定</el-button
        >
      </div>
    </el-dialog>

   
  </div>
</template>

<script>
export default {
  name: "users",
  data() {
    return {
      // 搜索
      keyword: "",
      //   表格数据
      tableData: [],
      //   分页
      pagenum: 1, //  第几页
      pagesize: 5, //  每页显示的条数
      total: 0,
      //  添加模态框的关闭
      dialogFormVisible: false,
      //  编辑弹框的关闭
      dialogFormVisible1: false,
      // 角色分配弹框的关闭
      dialogFormVisible2:false,
      //    添加的数据
      ruleForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      //   添加  编辑数据的验证
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        mobile: [{ required: true, message: "请输入手机号", trigger: "blur" }],
      },
      //   编辑的数据
      ruleForm1: {
        role_id: "", 
        email: "",
        mobile: "",
      }, 
       //   角色列表的数据
      ruleForm2: {}, 
      userInfo:[],
      // 选中的角色
      roleId:"",
    };
  },
  mounted() {
    this.getdata();   
  },
  methods: {
    // 角色分配请求的接口
   async submitForm2() {
    let userid=this.userInfo.id
      var resule=await this.$axios({
        url:`/api/private/v1/users/${userid}/roles`,
        method:"PUT",
        data:{
          id:userid,
          rid:this.roleId
        }
      }).catch(err=>err)
      console.log(resule);
     if(resule.data.status!==200) return this.$message.error("角色设置失败")
     this.$message.success("角色设置成功")
     
  
    }, 
    // 角色分配的对话框
   async  handleAdd(index,user){
     this.dialogFormVisible2 = true;    
     this.userInfo=user
     console.log(this.userInfo,'this.userInfo');
     let {data:res}=await this.$axios({
      url:'/api/private/v1/roles'
     }).catch(err=>err)
     this.ruleForm2=res.data
    }, 
    // 清空搜索框
    clearsearch() {
      (this.keyword = ""), (this.pagenum = 1);
      this.getdata();
    },
    // 执行搜索
    search() {
      this.pagenum = 1;
      this.getdata();
    },
    // 修改用户状态
    async changeState(row) {
      let { id, mg_state } = row;
      let { data: res } = await this.$axios({
        url: `/api/private/v1/users/${id}/state/${mg_state}`,
        method: "put",
      });
      console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("修改用户状态失败");
      this.$message.success("修改用户状态成功");
    },
    // 编辑  请求接口 
    submitForm1() {
      this.$refs.ruleForm1.validate(async (valid) => {
        if (valid) {    
        //   this.$message(result.data.meta.msg);
          var res = await this.$axios({
            url: `/api/private/v1/users/${this.ruleForm1.id}`,
            method: "put",
            data:this.ruleForm1
          });
          console.log(res, "编辑用户");
          this.getdata();
          this.dialogFormVisible1 = false;
          this.ruleForm1 = {};
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }, 
    //  编辑
    handleEdit(index, row) {
      console.log(index, row);
      this.dialogFormVisible1 = true;
      this.ruleForm1 = row;
    },
    //  删除
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          var res = await this.$axios({
            url: `/api/private/v1/users/${row.id}`,
            method: "delete",
          });
          console.log(res, "删除用户");
          this.getdata();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //  每页显示的条数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pagesize = val;
      this.getdata();
    },
    //   当前页数
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pagenum = val;
      this.getdata();
    },
    // 添加 请求接口
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) { 
          var res = await this.$axios({
            url: "/api/private/v1/users",
            method: "post",
            data: this.ruleForm,
          });
          console.log(res, "添加用户");
          this.getdata();
          this.dialogFormVisible = false;
          this.ruleForm = {};
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 添加打开模态框
    add() {
      this.dialogFormVisible = true;
    },
    // 渲染
    async getdata() {
      var resule = await this.$axios({
        url: "/api/private/v1/users",
        method: "get",
        params: {
          query: this.keyword,
          pagenum: this.pagenum,
          pagesize: this.pagesize,
        },
      }).catch((err) => console.log(err));
      console.log(resule.data.data.users, "users");
      this.tableData = resule.data.data.users;
      this.total = resule.data.data.total;
    },
  },
};
</script>
 

<style lang="scss" scoped>
 
  
</style>